package com.leyou.cart.service.impl;

import com.leyou.cart.entity.Cart;
import com.leyou.cart.service.ICartService;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理请求和响应的方法
 *
 * @version V1.0
 * @package com.leyou.cart.service.impl
 * @description:
 * @author: pc
 * @date: 2019/7/12 17:34
 */
@Slf4j
@Service("cartService")
public class ICartServiceImpl implements ICartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "ly:cart:uid:";

    /**
     * 添加购物车
     * */
    @Override
    public void saveCart(Cart cart) {
        //获取用户信息，判断是否有购物车，购物车中是否有数据
        BoundHashOperations<String, String, String> hashOps = queryUserHolderAndHashOps();
        //获取商品的skuId
        String hashKey = cart.getSkuId().toString();
        //根据商品的Id，查询购物车中是否已存在该商品
        Boolean isExists = hashOps.hasKey(hashKey);
        //如果商品为空，则添加商品
        if (isExists != null && isExists) {
            //获得该商品的json数据
            String hashJson = hashOps.get(hashKey);
            //将数据转为对象
            Cart cacheCart = JsonUtils.toBean(hashJson, Cart.class);
            //原有数量+新增数量
            assert cacheCart != null;
            cacheCart.setNum(cacheCart.getNum() + cart.getNum());
            //重新添加会购物车中
            hashOps.put(hashKey, JsonUtils.toString(cacheCart));
        } else {
            hashOps.put(hashKey, JsonUtils.toString(cart));
        }
    }

    /**
     * 购物车批量添加商品
     * */
    @Override
    public void saveCartList(List<Cart> carts) {
        for (Cart cart : carts) {
            saveCart(cart);
        }
    }

    /**
    * 删除已下单的购物车中的商品
    * */
    @Override
    public void deleteCart(String userId,Long skuId) {
        try {
            if (skuId == null) {
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
            }
            String hashKey = skuId.toString();
            if (userId == null) {
                //获得用户信息
                UserInfo user = UserHolder.getUser();
                //得到用户id
                userId = KEY_PREFIX + user.getId().toString();
                Long delCount = this.redisTemplate.boundHashOps(userId).delete(hashKey);
                if (delCount != 1) {
                    throw new LyException(ExceptionEnum.DELETE_CART_ERROR);
                }
            }else {
                userId = KEY_PREFIX + userId;
                Long delCount = this.redisTemplate.boundHashOps(userId).delete(hashKey);
                if (delCount != 1) {
                    throw new LyException(ExceptionEnum.DELETE_CART_ERROR);
                }
            }
        } catch (LyException e) {
            log.error("删除购物车中已下单商品失败，原因：{}",e.getMessage(),e);
            throw new LyException(ExceptionEnum.DELETE_CART_ERROR);
        }
    }

    /**
     * 查询购物车
     * */
    @Override
    public List<Cart> queryCartList() {
        //获取用户信息，判断是否有购物车，购物车中是否有数据
        BoundHashOperations<String, String, String> hashOps = queryUserHolderAndHashOps();
        List<String> carts = hashOps.values();
        if (carts == null) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        return carts.stream().map(json -> JsonUtils.toBean(json, Cart.class)).collect(Collectors.toList());
    }

    /**
     * 修改购物车数据
     * */
    @Override
    public void updateCart(Long skuId, Integer num) {
        //获取用户信息，判断是否有购物车，购物车中是否有数据
        BoundHashOperations<String, String, String> hashOps = queryUserHolderAndHashOps();
        String hashKey = skuId.toString();
        Boolean isExists = hashOps.hasKey(hashKey);
        //判断商品是否为空
        if (isExists == null && !isExists) {
            log.error("购物车商品不存在，商品：{}，原有:{}", skuId);
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        String hashValue = hashOps.get(hashKey);
        Cart cart = JsonUtils.toBean(hashValue, Cart.class);
        assert cart != null;
        cart.setNum(num);
        hashOps.put(hashKey, JsonUtils.toString(cart));

    }


    private BoundHashOperations<String, String, String> queryUserHolderAndHashOps() {
        //获得用户信息
        UserInfo user = UserHolder.getUser();
        //得到用户id
        String key = KEY_PREFIX + user.getId().toString();
        //判断是否有购物车
        Boolean bool = redisTemplate.hasKey(key);
        if (bool == null && bool) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        Long size = hashOps.size();
        if (size == null && size < 0) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        return hashOps;
    }
}
